<template>
	<a-modal :width="1350" :visible="visible" title="视频封面" :mask-closable="false" @ok="handleOk" @cancel="handleClose" centered>
		<div class="main_con">
			<div id="phoneConCover" class="left_phone_view" v-if="visible">
				<a-spin style="width:100%; height: 640px;" :spinning="loading">
					<DraggableContainer :style="resizableStyle" :referenceLineColor="'white'">
						<!-- 移动容器 -->
						<Vue3DraggableResizable v-show="item.copywriting" v-for="(item, index) in coverList"
							:key="'art_con'+index" :initW="coverList[index].width" :initH="coverList[index].height"
							v-model:x="coverList[index].elLeft" v-model:y="coverList[index].elTop"
							v-model:w="coverList[index].width" v-model:h="coverList[index].height"
							v-model:active="coverList[index].active" :draggable="true" :resizable="true" :parent="true">
							<div @click.stop="getPosition(index)" :style="coverStyle(item, index)">{{item.copywriting}}
							</div>
						</Vue3DraggableResizable>
					</DraggableContainer>
				</a-spin>
			</div>
			<div class="right_set_con">
				<div class="cover_con">
					<!-- {{ coverForm.poster_url }} -->
					<div class="cover_title">封面时长：</div>
					<div class="cover_value" style="transform: translateY(-5px);">
						<a-select style="width: 150px;" placeholder="请选择" v-model:value="coverForm.cover_duration">
							<a-select-option :value="0.05">0.05秒</a-select-option>
							<a-select-option :value="0.25">0.25秒</a-select-option>
							<a-select-option :value="0.5">0.5秒</a-select-option>
							<a-select-option :value="0.75">0.75秒</a-select-option>
							<a-select-option :value="1">1秒</a-select-option>
							<a-select-option :value="1.5">1.5秒</a-select-option>
							<a-select-option :value="2">2秒</a-select-option>
						</a-select>
					</div>
					<div class="cover_title" style="margin-left: 20px;">封面背景：</div>
					<div class="cover_value" style="transform: translateY(-5px);">
						<div class="custom_upload" @click="handleChooseMaterial" v-if="!coverForm.poster_url">
							<PlusOutlined />
							<div class="upload_txt">从素材库选择</div>
						</div>
						
						<div class="custom_upload" @click="handleChooseMaterial" v-else>
							<div class="operate_con">
								<DeleteOutlined style="color: #000; margin-left: 10px;" @click.stop="deleteImage" />
							</div>
							<img :src="coverForm.poster_url" alt="" />
						</div>
						
						<span style="color: #999;">若不选择封面背景，将默认显示视频画面～</span>
					</div>
				</div>

				<div class="cover_con">
					<div class="cover_title">封面文字：</div>
					<div class="cover_value" style="height: 475px; width: calc(100% - 90px);"  id="coverConBox">
						<a-card class="card_item" :id="'cover_'+card_index" style="width: 100%" v-for="(card_item, card_index) in coverList"
							:key="card_index">
							<template #title>
								<span style="font-weight: bold; font-size: 15px;">标题{{card_index + 1}}</span>
							</template>
							<template #extra>
								<DeleteOutlined @click="deleteForm(card_index)" class="delete_icon" />
							</template>
							<div class="form_con">
								<div class="left_form_con">
									<div class="form_item" style="align-items: flex-start;">
										<div class="form_title">文案</div>
										<div class="form_value">
											<a-textarea :bordered="false" style="border: none;
												background-color: #fafafa; border: 1px solid #eee;
												border-radius: 10px;"  v-model:value="coverList[card_index].copywriting" placeholder="请输入"
												:auto-size="{ minRows: 3, maxRows: 3 }" />
										</div>
									</div>
									<div class="form_item" style="margin-top: 15px;">
										<div class="form_title">字体</div>
										<div class="form_value">
											<a-select @change="value=>handleSelectChange(value, card_index)"
												v-model:value="coverList[card_index].typeface" placeholder="请输入"
												style="width: 48%;" :options="typefaceOptions"></a-select>
								
											<a-select v-model:value="coverList[card_index].font_size" placeholder="请选择"
												style="width: 48%;" :options="fontsizeOptions"></a-select>
										</div>
									</div>
									
									<div class="form_item" style="justify-content: flex-start">
										<div class="form_title">透明度</div>
										<div style="margin-left: 10px; width: 300px;">
											<a-row>
												<a-col :span="12">
													<a-slider v-model:value="coverList[card_index].opacity" :min="0" :max="1" :step="0.01" />
												</a-col>
												<a-col :span="4">
													<a-input-number v-model:value="coverList[card_index].opacity" :min="0"
														:max="1" :step="0.01" style="width: 150px;margin-left: 13px" />
												</a-col>
											</a-row>
										</div>
									</div>
								</div>
								<div class="right_form_con">
									<div class="form_item" style="justify-content: flex-start;">
										<div class="form_title">左右对齐</div>
										<div class="align_type">
											<div class="type_item" @click="chooseAlignType(item.value, card_index)"
												:class="card_item.align_type == item.value?'active':''"
												v-for="(item, index) in alignType" :key="index">
												<a-tooltip>
													<template #title>{{item.name}}</template>
													<cu-icon :type="item.icon" />
												</a-tooltip>
											</div>
										</div>
								
										<div class="form_title" style="margin-left: 10px;">上下对齐</div>
										<div class="align_type">
											<div class="type_item" @click="chooseVerticleType(item.value, card_index)"
												:class="card_item.verticle_position == item.value?'active':''"
												v-for="(item, index) in verticleType" :key="index">
												<a-tooltip>
													<template #title>{{item.name}}</template>
													<cu-icon :type="item.icon" />
												</a-tooltip>
											</div>
										</div>
									</div>
									<div class="form_item" style="margin: 15px 0; justify-content: flex-start;">
										<div class="form_title">文字颜色</div>
										<color-picker v-model:hex="coverList[card_index].color" :show-opacity="false" :btn-style="{
											width: '64px',
											height: '32px',
											marginLeft: '10px'
										}" />
										<div class="form_title">背景色</div>
										<color-picker v-model:hex="coverList[card_index].backgroundColor" :show-opacity="false"
											:btn-style="{
											width: '64px',
											height: '32px',
											marginLeft: '10px'
										}" />
										
										<a-button v-show="coverList[card_index].backgroundColor" type='link' @click="coverList[card_index].backgroundColor = ''">清除背景色</a-button>
									</div>
									
									<div class="form_item" style="margin: 15px 0; justify-content: flex-start;">
										<div class="form_title">过度效果</div>
										<a-button @click="chooseTransition(card_item, card_index)" style="width: 100px; margin-left: 10px;">选择</a-button>
										<div class="form_title" style="margin-left: 10px;">字体特效</div>
										<a-button @click="chooseSpecial(card_item, card_index)" style="width: 100px; margin-left: 10px;">选择</a-button>
									</div>
									
									<div class="form_item" style="margin: 15px 4px; justify-content: flex-start; font-size: 12px; color: #2878FF; height: 23px;">
										<span style="margin-right: 10px; flex-shrink: 0;" v-if="card_item.transitionKey['in']">淡入：{{matchData.transitions[card_item.transitionKey['in']]}};</span>
										<span style="margin-right: 10px; flex-shrink: 0;" v-if="card_item.transitionKey['out']">淡出：{{matchData.transitions[card_item.transitionKey['out']]}};</span>
										<span v-if="card_item.specialKey">特效：{{matchData.effects[card_item.specialKey]}};</span>
									</div>
								</div>
							</div>
						</a-card>
						<div class="add_btn">
							<a-button type="dashed" block @click="addForm">
								<template #icon>
									<PlusOutlined />
								</template>
								添加标题
							</a-button>
						</div>
					</div>
				</div>
			</div>
		</div>

		<chooseMaterial :visible="chooseVisible" @close="closeChoose" />
		<!-- 预览图片 -->
		<materialPreview :visible="previewVisible" :materialDetail="currentMaterial" @close="closePreview" />
		
		<transitionEffect @close="closeTansition" :visible="transitionVisible" :transitionKey="currentTransitionKey" />
		<specialEffects @close="closeSpecial" :visible="specialVisible" :specialKey="currentSpecialKey" />
	</a-modal>
</template>

<script>
	import {
		defineComponent,
		ref,
		reactive,
		toRefs,
		watch,
		computed,
		nextTick
	} from 'vue';
	import {
		message
	} from 'ant-design-vue';
	import {
		PlusOutlined,
		DeleteOutlined,
		AlignCenterOutlined,
		AlignLeftOutlined,
		AlignRightOutlined,
		StopOutlined,
		EyeOutlined
	} from '@ant-design/icons-vue';
	import chooseMaterial from "./chooseMaterial.vue";
	import request from "../../../../../../common/utils/request";
	import materialPreview from '../../sourceMaterial/modules/materialPreview.vue';
	
	import {
		DraggableContainer
	} from 'vue3-draggable-resizable';
	import Vue3DraggableResizable from 'vue3-draggable-resizable';
	//default styles
	import 'vue3-draggable-resizable/dist/Vue3DraggableResizable.css';
	
	import ColorPicker from "colorpicker-v3";
	import "colorpicker-v3/style.css";
	
	import transitionEffect from '../modules/transitionEffect.vue';
	import specialEffects from '../modules/specialEffects.vue';
	import matchData from '../js/match_data.js';
	import store from '@/store';
	export default defineComponent({
		props: {
			coverObj: {
				type: Object,
				default: ()=>{return {}}
			},
			visible: {
				type: Boolean,
				default: false
			}
		},
		components: {
			PlusOutlined,
			DeleteOutlined,
			AlignCenterOutlined,
			AlignLeftOutlined,
			AlignRightOutlined,
			chooseMaterial,
			StopOutlined,
			EyeOutlined,
			materialPreview,
			DraggableContainer,
			Vue3DraggableResizable,
			ColorPicker,
			transitionEffect,
			specialEffects
		},
		setup(props, context) {
			const state = reactive({
				currentTransitionKey: {in: '', out: ''},
				currentSpecialKey: '',
				specialVisible: false,
				transitionVisible: false,
				currentCardIndex: 0,
				coverForm: {
					cover_duration: 0.05,
					poster_url: ''
				},
				loading: false,
				coverList: [],
				alignType: [{
					icon: 'icon-zuoduiqi',
					name: '左',
					value: 'left'
				}, {
					icon: 'icon-juzhongduiqi',
					name: '居中',
					value: 'center'
				}, {
					icon: 'icon-youduiqi',
					name: '右',
					value: 'right'
				}],
				verticleType: [{
					icon: 'icon-chuizhidingduiqi_duiqicaozuo_jurassic',
					name: '上',
					value: 'top'
				}, {
					icon: 'icon-chuizhijuzhongduiqi_duiqicaozuo_jurassic',
					name: '居中',
					value: 'center'
				}, {
					icon: 'icon-chuizhididuiqi_duiqicaozuo_jurassic',
					name: '下',
					value: 'right'
				}],
				typefaceOptions: [],
				fontsizeOptions: [{
					label: '12',
					value: 12
				},{
					label: '14',
					value: 14
				},{
					label: '18',
					value: 18
				},{
					label: '24',
					value: 24
				},{
					label: '32',
					value: 32
				},{
					label: '36',
					value: 36
				},{
					label: '44',
					value: 44
				},{
					label: '48',
					value: 48
				},{
					label: '64',
					value: 64
				},{
					label: '80',
					value: 80
				}],
				chooseVisible: false,
				currentMaterial: {},
				previewVisible: false
			})

			const generateRandomString = () => {
			    let randomString = '';
			    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
			    const charactersLength = characters.length;
			    for (let i = 0; i < 6; i++) {
			      randomString += characters.charAt(Math.floor(Math.random() * charactersLength));
			    }
			    return randomString;
			}
			
			const handleOk = () => {
				let flag = false
				state.coverList.map(item=> {
					if(!item.copywriting && !state.coverForm.poster_url){
						flag = true
					}
					let font_family = state.typefaceOptions.find(v=>v.material_url == item.typeface)?.font_family
					let font_name = state.typefaceOptions.find(v=>v.material_url == item.typeface)?.name
					item.font_family = font_family
					item.font_name = font_name
				})
				console.log(state.coverList, state.coverForm, '选择封面11111');
				const obj = {
					name: props.coverObj?.name?props.coverObj.name:generateRandomString(),
					list: state.coverList,
					duration: state.coverForm.cover_duration,
					poster_url: state.coverForm.poster_url,

				}
				
				if(flag) {
					message.warn('封面与封面文字至少选择一个')
					return
				}
				context.emit('close', obj)
			}
			
			const handleClose = () => {
				context.emit('close')
			}
			
			const addForm = () => {
				let material_url = state.typefaceOptions.find(item => item.name == '站酷快乐体').material_url
				state.coverList.push({
					width: 200,
					height: 50,
					position: 'center',
					typeface: material_url,
					copywriting: '',
					align_type: 'center',
					font_size: 32,
					elLeft: 0, // 元素的左偏移量
					elTop: 0, // 元素的右偏移量
					active: true,
					color: '#FFF000',
					backgroundColor: '',
					verticle_position: 'center',
					opacity: 1,
					specialKey: '',
					transitionKey: {in: '', out: ''},
				})
				state.coverList[state.coverList.length - 1].backgroundColor = '#ffffff'
				nextTick(()=>{
					state.coverList[state.coverList.length - 1].backgroundColor = ''
				})
				state.loading = true
				customFont('HappyZcool-2016', material_url)
			}
			
			const radioType = computed(()=>store.getters.clipJSON?.aspect_ratio)
			
			const resizableStyle = computed(() => {
				return {
					backgroundImage: `url(https://ui.biaodianyun.com/dy-saas/admin-pc/assets/bg_cover-d353011d.png), url(${state.coverForm.poster_url}), url(https://hf.pigcms.com/static/wxapp/images/phone_black_back.png)`,
					backgroundSize: '100% auto',
					backgroundPosition: 'center center',
					backgroundRepeat: 'no-repeat',
					width: '360px',
					height: radioType.value == '1:1'?'360px':radioType.value == '16:9'?'202.5px':'640px'
				}
			})
			
			const coverStyle = computed(() => {
				return function(item, index) {
					let font_family = state.typefaceOptions.find(v => v.material_url == item.typeface)
						?.font_family
					return {
						'overflow': 'hidden',
						'cursor': 'grab',
						'font-family': font_family,
						'font-size': item.font_size + 'px',
						'width': item.width + 'px',
						'height': item.height + 'px',
						'color': item.color,
						'background-color': item.backgroundColor,
						'display': 'flex',
						'align-items': item.verticle_position == 'top' ? 'start' : item
							.verticle_position == 'center' ? 'center' : 'end',
						'justify-content': item.align_type == 'left' ? 'start' : item.align_type ==
							'center' ? 'center' : 'end',
						'opacity': item.opacity
					}
				}
			})
			
			const deleteForm = (index) => {
				if (state.coverList.length == 1) {
					message.warn('至少需要一个标题')
					return
				}
				state.coverList.splice(index, 1)
			}
			
			const getPosition = (index) => {
				const dom = document.getElementById('cover_'+index)
				const scrollCon = document.getElementById('coverConBox')
				scrollCon.scrollTo({
					top: dom.offsetTop - 220,
					behavior: 'smooth'
				})
			}
			
			const getFontClass = () => {
				state.typefaceOptions = []
				request.get('/work_ai', '/user/shotstack/material/fonts/list').then(res=>{
					res.result.map(item=>{
						item.label = item.name
						item.value = item.material_url
						state.typefaceOptions.push(item)
					})
					console.log(state.typefaceOptions, 'state.typefaceOptions');
					if(!props.coverObj?.list){
						let material_url = state.typefaceOptions.find(item => item.name == '站酷快乐体').material_url
						state.coverList = [{
							width: 200,
							height: 50,
							position: 'center',
							typeface: material_url,
							copywriting: '',
							align_type: 'center',
							font_size: 32,
							elLeft: 0, // 元素的左偏移量
							elTop: 0, // 元素的右偏移量
							active: true,
							color: '#FFF000',
							backgroundColor: '',
							verticle_position: 'center',
							opacity: 1,
							specialKey: '',
							transitionKey: {in: '', out: ''},
						}]
						state.coverList[0].backgroundColor = '#ffffff'
						nextTick(()=>{
							state.coverList[0].backgroundColor = ''
						})
						state.coverForm.poster_url = ''
						state.coverForm.cover_duration = 0.05
						state.loading = true
						customFont('HappyZcool-2016', material_url)
					}
				})
			}
			
			const customFont = (name, url) => {
				const fontFace = new FontFace(name, `url(${url})`);
				fontFace.load().then(() => {
					document.fonts.add(fontFace);
					state.loading = false
				}).catch((error) => {
					console.error(error);
					state.loading = false
				});
			}
			
			const handleSelectChange = (value) => {
				state.loading = true
				let font_family = state.typefaceOptions.find(item => item.value == value).font_family
				console.log(font_family, 'font_family');
				customFont(font_family, value)
			}
			
			const chooseAlignType = (value, index) => {
				state.coverList[index]['align_type'] = value
			}
			
			const chooseVerticleType = (value, index) => {
				state.coverList[index]['verticle_position'] = value
			}
			
			watch(() => props.visible, val => {
				if(val){
					getFontClass()
				}
				if(val && props.coverObj && props.coverObj.list?.length>0){
					console.log(props.coverObj.poster_url, 'url');
					state.coverList = JSON.parse(JSON.stringify(props.coverObj.list))
					state.coverForm.cover_duration = props.coverObj.duration
					state.coverForm.poster_url = props.coverObj.poster_url
					state.loading = true
					state.coverList.map((item, index)=>{
						customFont(item.font_family, item.typeface)
						if(!item.backgroundColor){
							state.coverList[index].backgroundColor = '#ffffff'
							nextTick(()=>{
								state.coverList[index].backgroundColor = ''
							})
						}
					})
				}
			})

			const handleChooseMaterial = () => {
				state.chooseVisible = true
			}
			
			const previewImage = () =>{
				state.previewVisible = true
			}
			
			const deleteImage = () =>{
				state.currentMaterial = {}
				state.coverForm.poster_url = ''
			}
			
			const closePreview = () => {
				state.previewVisible = false
			}

			const closeChoose = (obj) => {
				state.chooseVisible = false
				if(obj){
					state.currentMaterial = obj
					state.coverForm.poster_url = obj.fileUrl
				}
			}
			
			const chooseTransition = (item, index) => {
				state.currentCardIndex = index
				state.currentTransitionKey = Object.assign({}, item.transitionKey)
				state.transitionVisible = true
			}
			
			const closeTansition = (key) => {
				if(key != 'close'){
					state.coverList[state.currentCardIndex].transitionKey = key
				}
				state.currentTransitionKey = {in: '', out: ''}
				state.transitionVisible = false
			}
			
			const chooseSpecial = (item, index) => {
				state.currentCardIndex = index
				state.currentSpecialKey = item.specialKey
				state.specialVisible = true
			}
			
			const closeSpecial = (key) => {
				if(key != 'close'){
					state.coverList[state.currentCardIndex].specialKey = key
				}
				state.currentSpecialKey = ''
				state.specialVisible = false
			}

			return {
				...toRefs(state),
				handleChooseMaterial,
				closeChoose,
				...toRefs(state),
				handleOk,
				addForm,
				handleClose,
				deleteForm,
				getPosition,
				getFontClass,
				handleSelectChange,
				chooseAlignType,
				chooseVerticleType,
				previewImage,
				deleteImage,
				closePreview,
				coverStyle,
				chooseTransition,
				closeTansition,
				chooseSpecial,
				closeSpecial,
				matchData,
				radioType,
				resizableStyle
			}
		}
	})
</script>

<style lang="less" scoped>
	
	:deep(.ss-card-head){
		height: 40px !important;
		min-height: 40px !important;
		width: 100%;
		display: flex;
		align-items: center;
		background: #e6e6e6;
		.ss-card-head-wrapper{
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: space-between;
			
			.ss-card-head-title{
				font-size: 14px;
			}
		}
	}
	
	.align_type {
		display: flex;
		align-items: center;
		justify-content: flex-start;
		transform: translateX(-10px);
	
		.type_item {
			margin-left: 20px;
			font-size: 20px;
			cursor: pointer;
	
			&.active {
				color: #2878FF;
			}
	
			&:hover {
				color: #2878FF;
			}
		}
	}
	
	.delete_icon {
		font-size: 16px;
		cursor: pointer;
	
		&:hover {
			color: red;
		}
	}
	
	.form_con {
		display: flex;
		justify-content: space-between;
	
		.left_form_con,
		.right_form_con {
			width: 50%;
	
			.form_item {
				width: calc(100% - 10px);
				display: flex;
				align-items: center;
				margin-top: 10px;
				justify-content: space-between;
	
				.form_title {
					width: 60px;
					text-align: right;
				}
	
				.form_value {
					width: calc(100% - 70px);
					display: flex;
					justify-content: space-between;
				}
			}
		}
	}

	.main_con {
		display: flex;
		align-items: center;
		justify-content: space-between;

		.left_phone_view {
			width: 360px;
			height: 640px;
			background-color: #000;
			background-image: url('https://ui.biaodianyun.com/dy-saas/admin-pc/assets/bg_cover-d353011d.png');
			background-size: 100% 100%;
			background-repeat: no-repeat;
			background-position: center center;
			position: relative;
			overflow: hidden;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.right_set_con {
			width: calc(100% - 370px);
			height: 640px;

			.cover_con {
				display: flex;
				align-items: flex-start;
				margin-top: 10px;

				.cover_title {
					width: 70px;
					font-size: 14px;
					color: #999;
				}

				.cover_value {
					
					overflow-y: scroll;
					
					&::-webkit-scrollbar {
						width: 6px;
					}
					
					&::-webkit-scrollbar-track {
						width: 5px;
						background-color: transparent;
						-webkit-border-radius: 4px;
						-moz-border-radius: 4px;
						border-radius: 4px;
					}
					
					&::-webkit-scrollbar-thumb {
						background-color: rgba(193, 193, 193, 0.5);
						background-clip: padding-box;
						min-height: 28px;
						-webkit-border-radius: 4px;
						-moz-border-radius: 4px;
						border-radius: 4px;
					}
					
					.custom_upload {
						width: 100px;
						height: 100px;
						border-radius: 10px;
						background: #f9f9f9 !important;
						border: 1px dashed #ddd;
						color: #696969;
						display: flex;
						align-items: center;
						justify-content: center;
						flex-direction: column;
						cursor: pointer;
						position: relative;
						.upload_txt {
							margin-top: 5px;
						}
						
						.operate_con{
							display: none;
							position: absolute;
							width: 100%;
							height: 100%;
							left: 0;
							top: 0;
							font-size: 17px;
						}
						&:hover{
							.operate_con{
								display: flex;
								align-items: flex-end;
								justify-content: flex-end;
								padding: 5px;
							}
						}
						
						img{
							max-height: 95%;
							max-width: 95%;
						}
					}

					.card_item {
						margin-top: 10px;

						&:nth-child(1) {
							margin-top: 0;
						}
					}

					.add_btn {
						bottom: 0;
						left: 0;
						margin-top: 10px;
					}

				}
			}
		}
	}
</style>